package com.chuangke.sinotrukbudget.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.chuangke.common.constant.Consts;
import com.chuangke.core.http.HttpResult;
import com.chuangke.core.id.IdManager;
import com.chuangke.dingtalk.DingTalkService;
import com.chuangke.flow.domain.FlowAuditResult;
import com.chuangke.sinotrukbudget.consts.BudgetContanst;
import com.chuangke.sinotrukbudget.service.BudgetBpcDrillDownService;
import com.chuangke.sinotrukbudget.service.BudgetBpcPlanService;
import com.chuangke.sinotrukbudget.service.impl.BudgetAccountServiceImpl1;

/**
 * bpc预算上报对象Controller
 *
 * @author chuangke
 * @date "2022-10-21"
 */
@RestController
@RequestMapping("/budget/plan")
public class BudgetBpcPlanController {

	@Autowired
	private BudgetBpcPlanService budgetBpcPlanService;

	@Autowired
	private BudgetBpcDrillDownService budgetBpcDrillDownService;

	@Autowired
	private DingTalkService dingTalkService;

	/**
	 * 审批界面的预算查询
	 *
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/list")
	public HttpResult list(@RequestBody Map<String, Object> params) {
		// calType的可用值：t_account和t_entity
		String status = (String) params.get("status");
		String calType = (String) params.get("caltype");
		String tCategory = (String) params.get("category");
		String time = (String) params.get("period");
		String control = (String) params.get("control");
		List<String> deptIds = (List<String>) params.get("deptids");
		List<String> accountIds = (List<String>) params.get("accountids");
		List<String> flowIds = (List<String>) params.get("flowIds");

		deptIds = handleParam(deptIds);
		accountIds = handleParam(accountIds);

		// 1为管控，0为不管控
		boolean isControl = StrUtil.isBlank(control) ? false : "1".equals(control);

		return HttpResult.ok(budgetBpcPlanService.listAuditBudget(isControl, status, calType, tCategory, time, deptIds,
				accountIds, flowIds));
	}

	/**
	 * 审批界面的预算明细查询
	 *
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/listdetail")
	public HttpResult listdetail(@RequestBody Map<String, Object> params) {
		// calType的可用值：t_account和t_entity
		String status = (String) params.get("status");
		String calType = (String) params.get("caltype");
		String tCategory = (String) params.get("category");
		String time = (String) params.get("period");
		List<String> deptIds = (List<String>) params.get("deptids");
		List<String> accountIds = (List<String>) params.get("accountids");
		List<String> flowIds = (List<String>) params.get("flowIds");

		deptIds = handleParam(deptIds);
		accountIds = handleParam(accountIds);

		return HttpResult.ok(budgetBpcPlanService.listAuditDetailBudget(status, calType, tCategory, time, deptIds,
				accountIds, flowIds));
	}

	/**
	 * 编制界面的预算查询
	 *
	 * @param params
	 * @return
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/listdetailbydept")
	public HttpResult listDetailByDept(@RequestBody Map<String, Object> params) {
		String status = (String) params.get("status");
		String tCategory = (String) params.get("category");
		String deptId = (String) params.get("deptid");
		String period = (String) params.get("period");
		return HttpResult.ok(budgetBpcPlanService.listEditBudget(status, tCategory, deptId, period));
	}

	/**
	 * 预算查询界面的数据
	 *
	 * @param params
	 * @return
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/listdetailbygukou")
	public HttpResult listDetailByGuikou(@RequestBody Map<String, Object> params) {
		String guiKouId = (String) params.get("guiKouId");
		String tCategory = (String) params.get("category");
		String deptId = (String) params.get("deptid");
		String period = (String) params.get("period");
		return HttpResult.ok(budgetBpcPlanService.listGuiKouBudget(tCategory, deptId, guiKouId, period));
	}

	/**
	 * 加载明细预算信息
	 *
	 * @param params
	 * @return
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/listaccountdetail")
	public HttpResult listAccountDetailByDept(@RequestBody Map<String, Object> params) {
		int a = 1, b = 1;
		if (a == b) {
//			throw new ChuangkeException("暂不支持业务预算查看");
		}
		String accountId = (String) params.get("accountid");
		String deptId = (String) params.get("deptid");
		deptId = "31201.INP";
		accountId = "6606400100";
		String category = "BUD_B1";
		return HttpResult.ok(budgetBpcDrillDownService.list(category, accountId, deptId));
	}

	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/flowid")
	public HttpResult loadFlowId(@RequestBody Map<String, Object> params) {
		String deptId = (String) params.get("deptid");
		String category = (String) params.get("category");
		String accountId = (String) params.get("accountid");
		String time = (String) params.get("period");
		accountId = handleParam(accountId);

		return HttpResult.ok(budgetBpcPlanService.getFlowId(deptId, category, accountId, time));
	}

	/**
	 * 预算保存
	 *
	 * @param params
	 * @return
	 */
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/save")
	public HttpResult save(@RequestBody Map<String, Object> params) {
		String period = (String) params.get("period");
		String deptId = (String) params.get("deptid");
		String category = (String) params.get("category");
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> bbpList = (List<Map<String, Object>>) params.get("bbpList");
		budgetBpcPlanService.save(category, deptId, period, bbpList);
		return HttpResult.ok();
	}

	/**
	 * 预算提交
	 *
	 * @param params
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping("/submit")
	public HttpResult submit(@RequestBody Map<String, Object> params) {
//		String status = (String) params.get("status");
		String category = (String) params.get("category");
		String deptId = (String) params.get("deptid");
		String time = (String) params.get("period");
		List<String> accountIds = (List<String>) params.get("accountids");

		accountIds = handleParam(accountIds);

		return HttpResult.ok(budgetBpcPlanService.submitBudget(category, time, deptId, accountIds));
	}

	/**
	 * 预算审批
	 *
	 * @param handler
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/audit")
	public HttpResult auditBatch(@RequestBody Map<String, Object> params) {
		long start = System.currentTimeMillis();
		// calType的可用值：t_account和t_entity
		String audit = (String) params.get("audit");
		String message = (String) params.get("message");
		String calType = (String) params.get("caltype");
		String tCategory = (String) params.get("category");
		String time = (String) params.get("period");
		List<String> deptIds = (List<String>) params.get("deptids");
		List<String> accountIds = (List<String>) params.get("accountids");

		deptIds = handleParam(deptIds);
		accountIds = handleParam(accountIds);

		FlowAuditResult result = budgetBpcPlanService.auditBudget(audit, message, calType, tCategory, time, deptIds,
				accountIds);

		long end = System.currentTimeMillis();
		System.out.println("用时：" + (end - start));
		return HttpResult.ok(result);
	}

	/**
	 * 预算取回
	 *
	 * @param handler
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@PreAuthorize("hasAuthority('login:action')")
	@PostMapping(value = "/revoke")
	public HttpResult revokeBatch(@RequestBody Map<String, Object> params) {
		// calType的可用值：t_account和t_entity
		String audit = (String) params.get("audit");
		String message = (String) params.get("message");
		String calType = (String) params.get("caltype");
		String tCategory = (String) params.get("category");
		String time = (String) params.get("period");
		List<String> deptIds = (List<String>) params.get("deptids");
		List<String> accountIds = (List<String>) params.get("accountids");

		deptIds = handleParam(deptIds);
		accountIds = handleParam(accountIds);

		FlowAuditResult result = budgetBpcPlanService.revokeBudget(audit, message, calType, tCategory, time, deptIds,
				accountIds);

		return HttpResult.ok(result);
	}
	
	@Autowired
	private BudgetAccountServiceImpl1 budgetAccountServiceImpl1;

//	@PreAuthorize("hasAuthority('login:action')")
	@GetMapping("/start")
	public HttpResult start() {
//		int size = budgetBpcPlanService.startFlowAndSubmit();
//		return HttpResult.ok(String.format("启动流程最多执行400条，本次执行%s条", size));
		List list = budgetAccountServiceImpl1.findList() ;
		return HttpResult.ok() ;
	}

	@GetMapping("/dingtest")
	public HttpResult dingtest(@RequestParam Map<String, Object> map) {
//        Map<String, Object> env = new HashMap<>();
//        env.put("T_ENTITY", "1021.INP");
//        env.put("T_TIME", "2023.INP");
//        SysGridModel model = sysViewModelFormulaService.loadDataByModelId("PXF", env);

		String accessToken = dingTalkService.getAccessToken();
//		String userId = "1608064332874129";// E2Nm2aoEfNgiE

		String unionid = "E2Nm2aoEfNgiE";
		String sourceId = BudgetContanst.DING_TALK_TODO_PREFIX + IdManager.nextId();
		String subject = "归口审批平台（BPAP）有待审核预算";
		dingTalkService.createTodo(accessToken, unionid, sourceId, subject);
//		List<QueryOrgTodoTasksResponseBodyTodoCards> todoList = dingTalkService.queryTodo(accessToken, unionid);
		return HttpResult.ok();

//		return HttpResult.ok(model);
	}

	/**
	 * 去除掉前台界面设置的缩进
	 *
	 * @param paramList
	 * @return
	 */
	private List<String> handleParam(List<String> paramList) {
		if (CollectionUtils.isEmpty(paramList)) {
			return new ArrayList<>();
		}
		paramList = paramList.stream().map(param -> param.replaceAll(Consts.BLANK_CHAR + "", ""))
				.collect(Collectors.toList());
		return paramList;
	}

	private String handleParam(String param) {
		return param.replaceAll(Consts.BLANK_CHAR + "", "");
	}

}
